<?php

namespace app\api\controller;

use app\api\model\Goods as GoodsModel;
use app\api\model\Order as OrderModel;
use app\common\controller\Api;

class Order extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];

    public function Create()
    {
        $param = $this->request->param();
        $user = $this->auth;
        $GoodsModel = new GoodsModel();
        $OrderModel = new OrderModel();
        $where['id']=$param['goods_id'];
        $where['deletetime']=null;
        $find=$GoodsModel->where($where)->find();
        if(empty($find)){
            $this->error('商品不存在');
        }
        if($find['inventory']<1){
            $this->error('库存不足');
        }
        $this->score_change($user->id,$find['score'],0,"购买商品",0);
        $data['user_id']=$user->id;
        $data['order_sn']=date('YmdHis') . mt_rand(1000, 9999).$user->id;
        $data['goods_id']=$find['id'];
        $data['goods_json']=json_encode($find,JSON_UNESCAPED_UNICODE);
        $data['score']=$find['score'];
        $data['createtime']=time();
        $OrderModel->save($data);
        $GoodsModel->where($where)->setDec('inventory');
        $this->success('');
    }
    public function List()
    {
        $param = $this->request->param();
        $user = $this->auth;
        $OrderModel = new OrderModel();
        if(!empty($param['status'])){
            $where['status']=$param['status'];
        }
        $where['user_id']=$user->id;
        $list=$OrderModel->where($where)->order('id desc')->paginate(10)->each(function($item,$key){
            $item['goods']=json_decode($item['goods_json'],true);
            $item['qrcode']="https://".$_SERVER['HTTP_HOST']."/qrcode/build?text=".$item['id'];
            return $item;
        });
        $this->success('',$list);
    }
    public function ListCount()
    {
        $param = $this->request->param();
        $user = $this->auth;
        $OrderModel = new OrderModel();
        if(!empty($param['status'])){
            $where['status']=$param['status'];
        }
        $where['user_id']=$user->id;
        $count=$OrderModel->where($where)->count('id');
        $this->success('',$count);
    }
    public function WriteOff()
    {
        $param = $this->request->param();
        $user = $this->auth;
        if($user->is_WriteOff!=1){
            $this->error('没有核销权限');
        }
        $OrderModel = new OrderModel();
        $where['id']=$param['id'];
        $where['status']=1;
        $find=$OrderModel->where($where)->find();
        if(empty($find)){
            $this->error('订单不存在或已核销');
        }
        $updata['status']=2;
        $updata['write_off_time']=time();
        $updata['write_off_user_id']=$user->id;
        $OrderModel->where($where)->update($updata);
        $this->success('');
    }

}
